package ftp

import (
	"encoding/json"
	"fmt"
	"gin/model"
	"sort"
	"strconv"
	"strings"
	"time"
)

// 开锁日志
func (p *DataParsing) parsingEconomyLog(catData []string, ftpInfoId int64) []model.DataEconomy {
	var logDate, LogTime, steamId, gameName, gameId, dataType string
	var DataTxt, eventType, itemName, itemNum, price, area, trader, traderBalance, traderAccount, onlineNum, hadCash, balance, gold string
	var end int
	var dataArr []model.DataEconomy

	for _, logTxt := range catData {
		DataTxt = ""
		eventType = ""
		itemName = ""
		itemNum = ""
		price = ""
		area = ""
		trader = ""
		traderBalance = ""
		traderAccount = ""
		onlineNum = ""
		hadCash = ""
		balance = ""
		gold = ""
		//fmt.Println("原始数据", logTxt)

		parts := strings.Split(logTxt, ":")
		//fmt.Println("分割数据", parts)
		timeParts := strings.Split(parts[0], "-")
		//fmt.Println("分割数据2", timeParts)
		//日期转换  年-月-日
		logDate = strings.Replace(timeParts[0], ".", "-", -1)
		//fmt.Println("转换数据1", catDate)
		//时间转换  时:分:秒
		Time := strings.Replace(timeParts[1], ".", ":", -1)
		//fmt.Println("转换数据2", catTime)
		layout := "2006-01-02 15:04:05"
		// 解析时间字符串
		//fmt.Println("解析时间格式为", catDate+" "+catTime)
		t, err := time.Parse(layout, logDate+" "+Time)
		if err != nil {
			fmt.Println("解析时间格式为", err.Error())
			LogTime = "0"
			//return
		}
		// 转换为 Unix 时间戳（秒）

		LogTime = strconv.FormatInt(t.Unix(), 10)
		logTime, _ := strconv.ParseInt(LogTime, 10, 64)
		//太平洋时间制  + 8 小时
		//logTime = logTime + 3600*8
		t = time.Unix(logTime, 0)
		logDate = t.Format("2006-01-02")

		hour, minute, second := t.Clock()
		Time = fmt.Sprintf("%02d:%02d:%02d", hour, minute, second)

		//开锁类型过滤
		start := strings.Index(logTxt, ": [")
		if start < 0 {
			dataType = ""
		} else {
			// 查找第二个单引号的位置
			end = strings.Index(logTxt[start+3:], "]")
			if end < 0 {
				dataType = ""
			} else {
				dataType = logTxt[start+3 : start+3+end]
			}
		}

		if dataType != "Trade" {
			//不是银行数据跳过
			continue
		}

		if strings.Contains(logTxt, "Tradeable (") {

			//物品名称
			start := strings.Index(logTxt, "e (")
			if start < 0 {
				itemName = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+3:], " (")
				if end < 0 {
					itemName = ""
				} else {
					itemName = logTxt[start+3 : start+3+end]
				}
			}

			//截取物品数量字段
			start = strings.Index(logTxt, "(")
			if start < 0 {
				DataTxt = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+3:], ") ")
				if end < 0 {
					DataTxt = ""
				} else {
					DataTxt = logTxt[start+3 : start+3+end]
				}
			}

			//物品数量
			start = strings.Index(DataTxt, "(x")
			if start < 0 {
				itemNum = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(DataTxt[start+2:], ")")
				if end < 0 {
					itemNum = ""
				} else {
					itemNum = DataTxt[start+2 : start+2+end]
				}
			}

			//交易类型判断
			start = strings.Index(logTxt, ")) ")
			if start < 0 {
				eventType = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+3:], " by")
				if end < 0 {
					eventType = ""
				} else {
					eventType = logTxt[start+3 : start+3+end]
				}
			}

			//fmt.Println("itemNum", itemNum)
			//游戏名称
			start = strings.Index(logTxt, " by ")
			if start < 0 {
				gameName = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+4:], "(")
				if end < 0 {
					gameName = ""
				} else {
					gameName = logTxt[start+4 : start+4+end]
				}
			}

			//截取数据 用于获取游戏id
			start = strings.Index(logTxt, "by ")
			if start < 0 {
				DataTxt = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+3:], "for")
				if end < 0 {
					DataTxt = ""
				} else {
					DataTxt = logTxt[start+3 : start+3+end]
				}
			}
			//游戏id
			start = strings.Index(DataTxt, "(")
			if start < 0 {
				steamId = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(DataTxt[start+1:], ")")
				if end < 0 {
					steamId = ""
				} else {
					steamId = DataTxt[start+1 : start+1+end]
				}
			}

			//商人区域
			start = strings.Index(logTxt, "trader ")
			if start < 0 {
				area = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+7:], "_")
				if end < 0 {
					area = ""
				} else {
					area = logTxt[start+7 : start+7+end]
				}
			}

			//截取数据用于交易员识别
			start = strings.Index(logTxt, "trader")
			if start < 0 {
				DataTxt = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+6:], " o")
				if end < 0 {
					DataTxt = ""
				} else {
					DataTxt = logTxt[start+6 : start+6+end]
				}
			}

			//商人识别
			start = strings.Index(DataTxt, "_")
			if start < 0 {
				trader = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(DataTxt[start+1+2:], ",")
				if end < 0 {
					trader = ""
				} else {
					trader = DataTxt[start+1+2 : start+2+end]
				}
			}

			//根据 交易类型判断 商人余额
			if eventType == "purchased" {
				start = strings.Index(logTxt, "store was ")
				if start < 0 {
					traderBalance = ""
				} else {
					// 查找第二个单引号的位置
					end = strings.Index(logTxt[start+10:], ",")
					if end < 0 {
						traderBalance = ""
					} else {
						//这里是 4  是越过 区域数据截取
						traderBalance = logTxt[start+10 : start+10+end]
					}
				}

				//价格
				start = strings.Index(logTxt, "for ")
				if start < 0 {
					price = ""
				} else {
					// 查找第二个单引号的位置
					end = strings.Index(logTxt[start+4:], " m")
					if end < 0 {
						price = ""
					} else {
						price = logTxt[start+4 : start+4+end]
					}
				}

			} else {
				start = strings.Index(logTxt, "store is ")
				if start < 0 {
					traderBalance = ""
				} else {
					// 查找第二个单引号的位置
					end = strings.Index(logTxt[start+9:], ",")
					if end < 0 {
						traderBalance = ""
					} else {
						//这里是 4  是越过 区域数据截取
						traderBalance = logTxt[start+9 : start+9+end]
					}
				}

				//价格
				start = strings.Index(logTxt, "for ")
				if start < 0 {
					price = ""
				} else {
					// 查找第二个单引号的位置
					end = strings.Index(logTxt[start+4:], " (")
					if end < 0 {
						price = ""
					} else {
						price = logTxt[start+4 : start+4+end]
					}
				}
			}

			//商人余额  第一项

			//商人余额  第2项
			start = strings.Index(logTxt, "new amount is ")
			if start < 0 {
				traderAccount = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+14:], ",")
				if end < 0 {
					traderAccount = ""
				} else {
					//这里是 4  是越过 区域数据截取
					traderAccount = logTxt[start+14 : start+14+end]
				}
			}
			//在线人数
			start = strings.Index(logTxt, "online: ")
			if start < 0 {
				onlineNum = ""
			} else {
				// 查找第二个单引号的位置
				onlineNum = logTxt[start+8:]
			}

		} else if strings.Contains(logTxt, "Before selling") {
			//交易之前的数据
			eventType = "Before selling"
			//商人区域
			start = strings.Index(logTxt, "trader ")
			if start < 0 {
				area = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+7:], "_")
				if end < 0 {
					area = ""
				} else {
					area = logTxt[start+7 : start+7+end]
				}
			}

			//截取数据用于交易员识别
			start = strings.Index(logTxt, "trader")
			if start < 0 {
				DataTxt = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+6:], " p")
				if end < 0 {
					DataTxt = ""
				} else {
					DataTxt = logTxt[start+6 : start+6+end]
				}
			}

			//商人识别
			start = strings.Index(DataTxt, "_")
			if start < 0 {
				trader = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(DataTxt[start+1+2:], ",")
				if end < 0 {
					trader = ""
				} else {
					trader = DataTxt[start+1+2 : start+1+2+end]
				}
			}

			//游戏名称
			start = strings.Index(logTxt, "player ")
			if start < 0 {
				gameName = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+7:], "(")
				if end < 0 {
					gameName = ""
				} else {
					gameName = logTxt[start+7 : start+7+end]
				}
			}

			//游戏id
			start = strings.Index(logTxt, "(")
			if start < 0 {
				steamId = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+1:], ")")
				if end < 0 {
					steamId = ""
				} else {
					steamId = logTxt[start+1 : start+1+end]
				}
			}

			//现金
			start = strings.Index(logTxt, "had ")
			if start < 0 {
				hadCash = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+4:], " cash")
				if end < 0 {
					hadCash = ""
				} else {
					hadCash = logTxt[start+4 : start+4+end]
				}
			}

			//存款
			start = strings.Index(logTxt, "cash, ")
			if start < 0 {
				balance = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+6:], " account")
				if end < 0 {
					balance = ""
				} else {
					balance = logTxt[start+6 : start+6+end]
				}
			}

			//存款
			start = strings.Index(logTxt, "e and ")
			if start < 0 {
				gold = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+6:], " gold")
				if end < 0 {
					gold = ""
				} else {
					gold = logTxt[start+6 : start+6+end]
				}
			}

			//商人余额
			start = strings.Index(logTxt, "r had ")
			if start < 0 {
				traderAccount = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+6:], " fu")
				if end < 0 {
					traderAccount = ""
				} else {
					traderAccount = logTxt[start+6 : start+6+end]
				}
			}

		} else if strings.Contains(logTxt, "Before purchasing") {

			eventType = "Before purchasing"
			//购买之前的数据
			//商人区域
			start = strings.Index(logTxt, "trader ")
			if start < 0 {
				area = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+7:], "_")
				if end < 0 {
					area = ""
				} else {
					area = logTxt[start+7 : start+7+end]
				}
			}

			//截取数据用于交易员识别
			start = strings.Index(logTxt, "trader")
			if start < 0 {
				DataTxt = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+6:], " p")
				if end < 0 {
					DataTxt = ""
				} else {
					DataTxt = logTxt[start+6 : start+6+end]
				}
			}
			//商人识别
			start = strings.Index(DataTxt, "_")
			if start < 0 {
				trader = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(DataTxt[start+1+2:], ",")
				if end < 0 {
					trader = ""
				} else {
					trader = DataTxt[start+1+2 : start+1+2+end]
				}
			}
			//游戏名称
			start = strings.Index(logTxt, "player ")
			if start < 0 {
				gameName = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+7:], "(")
				if end < 0 {
					gameName = ""
				} else {
					gameName = logTxt[start+7 : start+7+end]
				}
			}

			//游戏id
			start = strings.Index(logTxt, "(")
			if start < 0 {
				steamId = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+1:], ")")
				if end < 0 {
					steamId = ""
				} else {
					steamId = logTxt[start+1 : start+1+end]
				}
			}

			//现金
			start = strings.Index(logTxt, "had ")
			if start < 0 {
				hadCash = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+4:], " cash")
				if end < 0 {
					hadCash = ""
				} else {
					hadCash = logTxt[start+4 : start+4+end]
				}
			}

			//存款
			start = strings.Index(logTxt, "cash, ")
			if start < 0 {
				balance = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+6:], " account")
				if end < 0 {
					balance = ""
				} else {
					balance = logTxt[start+6 : start+6+end]
				}
			}

			//存款
			start = strings.Index(logTxt, "e and ")
			if start < 0 {
				gold = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+6:], " gold")
				if end < 0 {
					gold = ""
				} else {
					gold = logTxt[start+6 : start+6+end]
				}
			}

			//商人余额
			start = strings.Index(logTxt, "r had ")
			if start < 0 {
				traderAccount = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+6:], " fu")
				if end < 0 {
					traderAccount = ""
				} else {
					traderAccount = logTxt[start+6 : start+6+end]
				}
			}
		} else if strings.Contains(logTxt, "After tradeable") {
			eventType = "After tradeable"
			//交易之后的数据
			//商人区域
			start = strings.Index(logTxt, "trader ")
			if start < 0 {
				area = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+7:], "_")
				if end < 0 {
					area = ""
				} else {
					area = logTxt[start+7 : start+7+end]
				}
			}

			//截取数据用于交易员识别
			start = strings.Index(logTxt, "trader")
			if start < 0 {
				DataTxt = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+6:], " p")
				if end < 0 {
					DataTxt = ""
				} else {
					DataTxt = logTxt[start+6 : start+6+end]
				}
			}

			//商人识别
			start = strings.Index(DataTxt, "_")
			if start < 0 {
				trader = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(DataTxt[start+1+2:], ",")
				if end < 0 {
					trader = ""
				} else {
					trader = DataTxt[start+1+2 : start+1+2+end]
				}
			}
			//游戏名称
			start = strings.Index(logTxt, "player ")
			if start < 0 {
				gameName = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+7:], "(")
				if end < 0 {
					gameName = ""
				} else {
					gameName = logTxt[start+7 : start+7+end]
				}
			}

			//游戏id
			start = strings.Index(logTxt, "(")
			if start < 0 {
				steamId = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+1:], ")")
				if end < 0 {
					steamId = ""
				} else {
					steamId = logTxt[start+1 : start+1+end]
				}
			}

			//现金
			start = strings.Index(logTxt, "has ")
			if start < 0 {
				hadCash = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+4:], " cash")
				if end < 0 {
					hadCash = ""
				} else {
					hadCash = logTxt[start+4 : start+4+end]
				}
			}

			//存款
			start = strings.Index(logTxt, "cash, ")
			if start < 0 {
				balance = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+6:], " bank")
				if end < 0 {
					balance = ""
				} else {
					balance = logTxt[start+6 : start+6+end]
				}
			}

			//存款
			start = strings.Index(logTxt, "e and ")
			if start < 0 {
				gold = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+6:], " gold")
				if end < 0 {
					gold = ""
				} else {
					gold = logTxt[start+6 : start+6+end]
				}
			}

			//商人余额
			start = strings.Index(logTxt, "r has ")
			if start < 0 {
				traderAccount = ""
			} else {
				// 查找第二个单引号的位置
				end = strings.Index(logTxt[start+6:], " fu")
				if end < 0 {
					traderAccount = ""
				} else {
					traderAccount = logTxt[start+6 : start+6+end]
				}
			}
		}

		//fmt.Println("eventType", eventType, itemName)
		//fmt.Println("数据为：", ftpInfoId, logDate, Time, LogTime, steamId, gameName, gameId, loginType, loginIp, location)

		onlineNum, _ := strconv.ParseInt(onlineNum, 10, 64)
		downloadFile := model.DataEconomy{FtpInfoId: ftpInfoId, Date: logDate, Time: Time, LogTime: logTime, SteamId: steamId, GameName: gameName, GameId: gameId,
			EventType: eventType, ItemName: itemName, ItemNum: itemNum, Price: price, Area: area, Trader: trader, TraderBalance: traderBalance, TraderAccount: traderAccount,
			OnlineNum: onlineNum, Balance: balance, Gold: gold, HadCash: hadCash}
		dataArr = append(dataArr, downloadFile)
	}

	//排序数据  进行数据整合成一行
	dataArrsortData := sortByLogDateThenSteamId(dataArr)

	var logTimeF int64

	var steamIdF string
	var saveStatus bool

	saveStatus = false
	var newData model.DataEconomy

	var goodsArr []GoodsItem

	var newDataArr []model.DataEconomy

	var payType string
	var online int64

	traderBalance = "-1"
	traderAccount = "-1"
	var goodsItemArrTxtStr string
	for _, dataF := range dataArrsortData {

		//初始化数据
		if logTimeF != dataF.LogTime || steamIdF != dataF.SteamId {

			logTimeF = dataF.LogTime
			steamIdF = dataF.SteamId
			if saveStatus {

				//这里修正如果是出售的情况下  没有 银行存款数据 那么 交易前和  交易后都是相同的
				if newData.StartBalance != "" && newData.EndBalance == "" {
					newData.EndBalance = newData.StartBalance
				}
				goodsItemArrTxt, _ := json.Marshal(goodsArr)
				if len(string(goodsItemArrTxt)) > 1000 {
					goodsItemArrTxtStr, _ = extractJSONItems(string(goodsItemArrTxt), 50)
				} else {
					goodsItemArrTxtStr = string(goodsItemArrTxt)
				}

				newData.GoodsJson = goodsItemArrTxtStr
				newData.EventType = payType
				newData.OnlineNum = online
				newData.Balance = traderBalance
				newData.TraderAccount = traderAccount

				/*
					调试代码  上面的 _ 改 key1  即可调试
					fmt.Println("dataF", dataF)
					for i := 0; i < key1; i++ {
						fmt.Println("dataArrsortData", dataArrsortData[i])
					}

					fmt.Println("newData", newData)

					panic(666)*/

				newDataArr = append(newDataArr, newData)
				//初始化json 结构体数据
				goodsArr = []GoodsItem{}
				payType = ""
				traderBalance = "-1"
				traderAccount = "-1"
				//fmt.Println("goodsArr", goodsArr)
			}

			newData = dataF
			//fmt.Println("goodsArr", newData)

		}
		switch dataF.EventType {
		//购买
		case "purchased":
			goods := GoodsItem{ItemName: dataF.ItemName, ItemNum: dataF.ItemNum, ItemPrice: dataF.Price}
			goodsArr = append(goodsArr, goods)
			payType = "purchased"
			online = dataF.OnlineNum
			break

		//出售
		case "sold":

			goods := GoodsItem{ItemName: dataF.ItemName, ItemNum: dataF.ItemNum, ItemPrice: dataF.Price}
			goodsArr = append(goodsArr, goods)
			payType = "sold"
			online = dataF.OnlineNum

			break
		//购买前
		case "Before purchasing":
			newData.StartBalance = dataF.Balance
			newData.StartGold = dataF.Gold
			newData.StartMoney = dataF.HadCash

			//理解为 出售上限
			traderBalanceNum, _ := strconv.ParseInt(traderBalance, 10, 64)
			Balance, _ := strconv.ParseInt(dataF.Balance, 10, 64)
			if traderBalanceNum < Balance {
				traderBalance = dataF.Balance
			}

			//理解为 购买上限
			traderAccountNum, _ := strconv.ParseInt(traderAccount, 10, 64)
			Account, _ := strconv.ParseInt(dataF.TraderAccount, 10, 64)
			if traderAccountNum < Account {
				traderAccount = dataF.TraderAccount
			}

			break
		//交易之后
		case "After tradeable":

			newData.EndBalance = dataF.Balance
			newData.EndGold = dataF.Gold
			newData.EndMoney = dataF.HadCash
			break
		//交易之前
		case "Before selling":
			newData.StartBalance = dataF.Balance
			newData.StartGold = dataF.Gold
			newData.StartMoney = dataF.HadCash
			break
		}

		saveStatus = true
	}
	//panic("停止")
	//p.Log.FtpLogGer(newDataArr)
	return newDataArr
}

type GoodsItem struct {
	ItemName  string
	ItemNum   string
	ItemPrice string // 假设价格以字符串形式存储，可能是为了处理货币格式
}

// 按  LogTime  和 SteamId 相同的进行排序
func sortByLogDateThenSteamId(data []model.DataEconomy) []model.DataEconomy {
	sort.Slice(data, func(i, j int) bool {
		if data[i].LogTime == data[j].LogTime {
			// 如果 LogDate 相同，则按 SteamId 排序
			return data[i].SteamId < data[j].SteamId
		}
		// 否则按 LogDate 排序
		return data[i].LogTime < data[j].LogTime
	})
	return data
}

func extractJSONItems(jsonStr string, count int) (string, error) {
	// 首先将JSON字符串解析为通用的interface{}类型
	var data interface{}
	err := json.Unmarshal([]byte(jsonStr), &data)
	if err != nil {
		return "", fmt.Errorf("JSON解析失败: %v", err)
	}

	// 检查是否为数组类型
	array, ok := data.([]interface{})
	if !ok {
		return "", fmt.Errorf("输入的JSON不是数组格式")
	}

	// 如果数组长度小于等于要提取的数量，直接返回原JSON
	if len(array) <= count {
		return jsonStr, nil
	}

	// 截取前count个元素
	extracted := array[:count]

	// 重新序列化为JSON字符串
	result, err := json.Marshal(extracted)
	if err != nil {
		return "", fmt.Errorf("JSON序列化失败: %v", err)
	}

	return string(result), nil
}
